padVector <- function(vector,desiredLength){
  if(length(vector) < desiredLength){
    paddingLength = desiredLength - length(vector)
    return(append(vector,rep(vector[length(vector)],paddingLength)))
  }
  return(vector)
}

extractData <- function(inputFile){
  #Read data and compute errors for each cluster
  inputData <- read.table(inputFile,header=TRUE)
  return(stepfun(c(0,inputData[,1],10000),c(0,0,inputData[,2],inputData[length(inputData[,2]),2])))
}


#############################################################################

# $1 - Directory where the .occ files corresponding to the different experiments are stored
# $2 - Experiment duration (seconds)
args <- commandArgs(trailingOnly = TRUE)
workingDirectory <- args[1]
occupation <- args[2]
rm(args)

#Set the directory containing the experiment results as current working directory
setwd(paste("/home/deste/argos2/user/jdestefani/results/Ecdf/",workingDirectory,"/",sep=""))
#List all the files containing information about occupation
if(occupation == "25"){
  resultsFiles <- list.files(pattern = "\\.o25$")
}
if(occupation == "50"){
  resultsFiles <- list.files(pattern = "\\.o50$")
}
resultsFiles <- sort(unlist(resultsFiles))


print("[STATUS] - Processing results file")
#Process every single file separately
printData <- lapply(resultsFiles,extractData)
resultsFiles <-  strsplit(resultsFiles,"\\.")
resultsFiles <- lapply(resultsFiles,function(x) return(x[2]))


print("[STATUS] - Producing plots")
#lineTypes <- c(1,2,4,5,6,1)
#colors <- rainbow(length(printData))
lineTypes <- c(1,2,4,5,6)
colors <- c("black","gray25","#606060","gray50","gray75","#DFDFDF")
pdf(paste(workingDirectory,occupation,"pdf",sep="."))
plot(range(0,10*as.numeric(1000)),range(0,1),type="n",xlab="Time steps",ylab="P(x)",main=paste("Time needed to reach ",occupation,"% occupation in each cluster across 50 trials"))
lapply(seq(length(printData)),FUN=function(x) plot(printData[[x]],add=TRUE,col=colors[x],lty=lineTypes[x],pch="."))
#legend(x="bottomright", c("Probabilistic","Informed","Naive") , cex=1, col=colors, lty=lineTypes, title="Method")
legend(x="bottomright", legend=resultsFiles , cex=1, col=colors, lty=lineTypes, title="Method")
dev.off()

rm(resultsFiles)
rm(printData)
#createTexGraph("t","$\\max_i(e_i(t))$",5,5,inputData[,1],maxErrorIntegrated[,1])
